package site.assad.web;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import site.assad.service.PMService;

import java.io.IOException;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2018/1/10 11:50
 * Description:
 */
public class PMWebSocketHandler extends AbstractWebSocketHandler{

    private static final Logger log = LogManager.getLogger();

    @Autowired
    private PMService pmService;
    private MessageSendThread thread ;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String city = message.getPayload().trim();
        log.debug("get: " + city);
        if(thread == null){
            thread = new MessageSendThread(session,city);
            thread.start();
        }
        thread.setCity(city);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if(thread != null)
            thread.kill();
    }

    private class MessageSendThread extends Thread{

        private volatile boolean isRunning = true;
        private WebSocketSession session ;
        private volatile String city;

        public MessageSendThread(WebSocketSession session, String city) {
            this.session = session;
            this.city = city;
        }

        public void setCity(String city) {
            this.city = city;
        }
        @Override
        public void run() {
            while(isRunning){
                try {
                    String sendMsg = pmService.getData(city);
                    log.debug("send:" + sendMsg);
                    session.sendMessage(new TextMessage(sendMsg));
                    Thread.sleep(1000);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                }
            }
        }

        public void kill(){
            isRunning = false;
        }
    }


}
